import pika
from config import RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_USER, RABBITMQ_PASSWORD


def create_queue(queue_name):
    """
    创建 RabbitMQ 队列
    """
    try:
        # 创建连接参数
        credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)
        parameters = pika.ConnectionParameters(
            host=RABBITMQ_HOST, port=RABBITMQ_PORT, credentials=credentials)
        # 建立连接
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        # 声明队列
        channel.queue_declare(queue=queue_name)
        connection.close()
        return f"Queue {queue_name} created successfully."
    except Exception as e:
        return f"Error creating queue: {str(e)}"


def send_message(queue_name, message):
    """
    向 RabbitMQ 队列发送消息
    """
    try:
        # 创建连接参数
        credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)
        parameters = pika.ConnectionParameters(
            host=RABBITMQ_HOST, port=RABBITMQ_PORT, credentials=credentials)
        # 建立连接
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        # 声明队列
        channel.queue_declare(queue=queue_name)
        # 发送消息
        channel.basic_publish(exchange='', routing_key=queue_name, body=message)
        connection.close()
        return f"Message '{message}' sent to queue {queue_name} successfully."
    except Exception as e:
        return f"Error sending message: {str(e)}"


def listen_to_queue(queue_name):
    try:
        credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)
        parameters = pika.ConnectionParameters(
            host=RABBITMQ_HOST,
            port=RABBITMQ_PORT,
            credentials=credentials
        )
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        channel.queue_declare(queue=queue_name)
        def callback(ch, method, properties, body):
            print(f"Received message: {body.decode()}")
            # 如果需要手动确认消息，可以取消注释以下行
            # ch.basic_ack(delivery_tag=method.delivery_tag)
        channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
        print('Waiting for messages. To exit press CTRL+C')
        channel.start_consuming()
    except Exception as e:
        print(f"Error listening to queue: {str(e)}")


def create_exchange(exchange_name, exchange_type='direct'):
    """
    创建 RabbitMQ 交换机
    """
    try:
        credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)
        parameters = pika.ConnectionParameters(
            host=RABBITMQ_HOST, port=RABBITMQ_PORT, credentials=credentials)
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        channel.exchange_declare(exchange=exchange_name, exchange_type=exchange_type)
        connection.close()
        return f"Exchange {exchange_name} created successfully."
    except Exception as e:
        return f"Error creating exchange: {str(e)}"


def send_message_to_exchange(exchange_name, routing_key, message):
    """
    向 RabbitMQ 交换机发送消息
    """
    try:
        credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)
        parameters = pika.ConnectionParameters(
            host=RABBITMQ_HOST, port=RABBITMQ_PORT, credentials=credentials)
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        channel.basic_publish(exchange=exchange_name, routing_key=routing_key, body=message)
        connection.close()
        return f"Message '{message}' sent to exchange {exchange_name} " \
               f"with routing key {routing_key} successfully."
    except Exception as e:
        return f"Error sending message to exchange: {str(e)}"
